import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

import '../model/music_progress.dart';

/**
 * 曲目进度数据服务
 *
 * 负责进度数据的存储和查询
 */
class MusicProgressService {
  Future<MusicProgress> get(String songId) {
    Future<SharedPreferences> pref = SharedPreferences.getInstance();
    return pref.then((SharedPreferences p) {
      String? progress = p.getString(_progressKey(songId));
      if (progress != null) {
        return MusicProgress.fromJson(jsonDecode(progress) as Map<String, dynamic>);
      }
      return MusicProgress.def(songId: songId);
    });
  }

  Future<void> save(MusicProgress? progress) {
    if (progress == null) {
      throw ArgumentError("progress or progress.songId is null");
    }

    Future<SharedPreferences> pref = SharedPreferences.getInstance();
    return pref.then((SharedPreferences p) {
      p.setString(_progressKey(progress.songId), jsonEncode(progress));
    });
  }

  String _progressKey(String songId) {
    return "progress_$songId";
  }
}